import { getUser } from '../../request'
import { Toast } from 'vant'

const username = localStorage.getItem('username')
const headerIcon = localStorage.getItem('headerIcon')
const token = localStorage.getItem('token')

export default {
  namespaced: true, // 启用命名空间
  state: {
    username,
    headerIcon,
    token
  },
  getters: {},
  mutations: {
    // 登录成功，更新状态
    LOGIN_SUCCESS (state, { username, headerIcon, token }) {
      console.log('修改 user 状态：', username, headerIcon, token)
      state.username = username
      state.headerIcon = headerIcon
      state.token = token
    },
    delUserInfo (state) {
      localStorage.removeItem('token')
      state.token = localStorage.getItem('token')
    }
  },
  actions: {
    loginAsync (store, { username, password }) {
      return getUser(username, password)
        .then(res => {
          console.log('登录处理：', res)
          const { data } = res.data
          console.log(data)
          if (res.data.code === 200 && data.status === 200) {
            const { username, headerIcon, token } = data.userInfo
            store.commit('LOGIN_SUCCESS', { username, headerIcon, token })
            return {
              status: 200
            }
          } else {
            Toast.fail('用户名或密码错误')
          }
        })
        .catch(err => {
          console.log('异常：', err)
        })
    }
  }
}
